---
layout: default
title: User guide
comments: true
locale: en
---
<div class="container developer-guide">
  <div class="row">

    <!-- Main content -->
    <div class="col-md-10">

      <!-- ************ -->
      <!-- INSTALLATION -->
      <!-- ************ -->

      <section id="installation">
        <h1 class="page-header">Installation</h1>

        <h2 id="installation-requirements">Requirements</h2>

        <ul class="list-group">
          <li class="list-group-item">EasyMock 3.5+ requires Java 1.6 and above</li>
          <li class="list-group-item">EasyMock 3.4- requires Java 1.5 and above</li>
          <li class="list-group-item">Objenesis (2.0+) must be in the classpath to perform class mocking</li>
        </ul>

        <h2 id="installation-using-maven">Using Maven</h2>

        <p>EasyMock is available in the Maven central repository. Just add the following dependency to your pom.xml:</p>

{% highlight xml %}
<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymock</artifactId>
  <version>{{site.latest_version}}</version>
  <scope>test</scope>
</dependency>
{% endhighlight %}

        <p>You can obviously use any other dependency tool compatible with the Maven repository.</p>

        <h2 id="installation-standalone">Standalone</h2>

        <ul class="list-group">
          <li class="list-group-item">Download the <a href="https://github.com/easymock/easymock/releases/download/easymock-{{site.latest_version}}/easymock-{{site.latest_version}}-bundle.zip">EasyMock zip file</a></li>
          <li class="list-group-item">It contains the <code>easymock-{{site.latest_version}}.jar</code> to add to your classpath</li>
          <li class="list-group-item">To perform class mocking, also add <a href="http://objenesis.org">Objenesis</a> to your classpath.</li>
          <li class="list-group-item">The bundle also contains jars for the javadoc, the tests, the sources and the samples</li>
        </ul>

        <h2 id="installation-android">Android <span class="badge">Since 3.2</span></h2>

        <p>EasyMock can be used on Android VM (Dalvik). Just add EasyMock and Dexmaker as dependencies of the apk project used to test your application. It is a good idea to exclude Cglib since Dexmaker is used instead.
          If you use Maven, the final required dependencies will look like this:</p>

        {% highlight xml %}
<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymock</artifactId>
  <version>{{site.latest_version}}</version>
</dependency>
<dependency>
  <groupId>org.droidparts.dexmaker</groupId>
  <artifactId>dexmaker</artifactId>
  <version>1.5</version>
</dependency>
        {% endhighlight %}

      </section>

      <!-- ******* -->
      <!-- MOCKING -->
      <!-- ******* -->

      <section id="mocking">
        <h1 class="page-header">Mocking</h1>

        <h2 id="mocking-first">The first Mock Object </h2>

        <p>We will now build a test case and toy around with it to understand the functionalities of EasyMock.
          You can also have a look at the <a href="https://github.com/easymock/easymock/tree/easymock-{{site.latest_version}}/core/src/samples/java/org/easymock/samples">samples</a>
          and the <a href="getting-started.html">Getting Started</a>.
        </p>
        <p>Our first test should check whether the removal of a non-existing document does <strong>not </strong> lead to a notification
          of the collaborator. Here is the test without the definition of the Mock Object:</p>

{% highlight java %}

import org.junit.*;

public class ExampleTest {

  private ClassUnderTest classUnderTest;

  private Collaborator mock;

  @Before
  public void setUp() {
    classUnderTest = new ClassUnderTest();
    classUnderTest.setListener(mock);
  }

  @Test
  public void testRemoveNonExistingDocument() {
    // This call should not lead to any notification
    // of the Mock Object:
    classUnderTest.removeDocument("Does not exist");
  }
}
{% endhighlight %}

        <p>For many tests using EasyMock, we only need a static import of methods of <code>org.easymock.EasyMock</code>.</p>

{% highlight java %}
import static org.easymock.EasyMock.*;
import org.junit.*;

public class ExampleTest {
  private ClassUnderTest classUnderTest;
  private Collaborator mock;
}
{% endhighlight %}

        <p>To get a Mock Object, we need to</p>

        <ol>
          <li>create a Mock Object for the interface we would like to simulate</li>
          <li>record the expected behavior</li>
          <li>switch the Mock Object to replay state</li>
        </ol>

        <p>Here is a first example:</p>

{% highlight java %}
@Before
public void setUp() {
  mock = mock(Collaborator.class); // 1
  classUnderTest = new ClassUnderTest();
  classUnderTest.setListener(mock);
}

@Test
public void testRemoveNonExistingDocument() {
  // 2 (we do not expect anything)
  replay(mock); // 3
  classUnderTest.removeDocument("Does not exist");
}
{% endhighlight %}

        <p>After activation in step 3, <code>mock</code> is a Mock Object for the <code>Collaborator</code> interface that expects no calls. This means that if we change our <code>ClassUnderTest</code> to call any of the interface's methods, the Mock Object will throw an <code>AssertionError</code>:</p>

{% highlight java %}
java.lang.AssertionError:
  Unexpected method call documentRemoved("Does not exist"):
    at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29)
    at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:44)
    at $Proxy0.documentRemoved(Unknown Source)
    at org.easymock.samples.ClassUnderTest.notifyListenersDocumentRemoved(ClassUnderTest.java:74)
    at org.easymock.samples.ClassUnderTest.removeDocument(ClassUnderTest.java:33)
    at org.easymock.samples.ExampleTest.testRemoveNonExistingDocument(ExampleTest.java:24)
      ...
{% endhighlight %}

        <h2 id="mocking-annotations">Using annotations <span class="badge">Since 3.2</span></h2>

        <p>There is a nice and shorter way to create your mocks and inject them to the tested class. Here is the example above, now using annotations:</p>

{% highlight java %}
import static org.easymock.EasyMock.*;
import org.easymock.EasyMockRunner;
import org.easymock.TestSubject;
import org.easymock.Mock;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(EasyMockRunner.class)
public class ExampleTest {

  @TestSubject
  private ClassUnderTest classUnderTest = new ClassUnderTest(); // 2

  @Mock
  private Collaborator mock; // 1

  @Test
  public void testRemoveNonExistingDocument() {
    replay(mock);
    classUnderTest.removeDocument("Does not exist");
  }
}
{% endhighlight %}

        <p>The <code>mock</code> is instantiated by the runner at step 1. It is then set by the runner, to the <code>listener</code> field on step 2.
          The <code>setUp</code> method can be removed since all the initialization was done by the runner.</p>

        <p>On top of that, since EasyMock 3.3, if you need to use another runner on you tests, a JUnit rule is also available to you. Both have the exact same behavior. Choosing one of the other is a matter of taste.</p>

{% highlight java %}
import static org.easymock.EasyMock.*;
import org.easymock.EasyMockRule;
import org.easymock.TestSubject;
import org.easymock.Mock;
import org.junit.Rule;
import org.junit.Test;

public class ExampleTest {

  @Rule
  public EasyMockRule mocks = new EasyMockRule(this);

  @TestSubject
  private ClassUnderTest classUnderTest = new ClassUnderTest();

  @Mock
  private Collaborator mock;

  @Test
  public void testRemoveNonExistingDocument() {
    replay(mock);
    classUnderTest.removeDocument("Does not exist");
  }
}
{% endhighlight %}

        <p>Finally, since EasyMock 4.1, JUnit 5 extensions are supported.</p>

{% highlight java %}
import static org.easymock.EasyMock.*;
import org.easymock.EasyMockExtension;
import org.easymock.TestSubject;
import org.easymock.Mock;
import org.junit.Rule;
import org.junit.Test;

@ExtendWith(EasyMockExtension.class)
public class ExampleTest {

  @TestSubject
  private ClassUnderTest classUnderTest = new ClassUnderTest();

  @Mock
  private Collaborator mock;

  @Test
  public void testRemoveNonExistingDocument() {
    replay(mock);
    classUnderTest.removeDocument("Does not exist");
  }
}
{% endhighlight %}

        <p>The annotation has an optional element, 'type', to refine the mock as a 'nice' mock or a 'strict' mock. Another optional annotation, 'name', allows setting of a name for the mock that will be used in the <code>mock()</code> call, which will appear in expectation failure messages for example. Finally, an optional element, "fieldName", allows specifying the target field name where the mock should be injected. Mocks are injected to any field in any <code>@TestSubject</code> that is of compatible type. If more than one mock can be assigned to the same field then this is considered an error. The <code>fieldName</code> qualifier can be used in this scenario to disambiguate the assignments.</p>

{% highlight java %}
@Mock(type = MockType.NICE, name = "mock", fieldName = "someField")
private Collaborator mock;

@Mock(type = MockType.STRICT, name = "anotherMock", fieldName = "someOtherField")
private Collaborator anotherMock;
{% endhighlight %}

        <h2 id="mocking-support">EasyMockSupport</h2>

        <p><code>EasyMockSupport</code> is a class that exist to help you keeping track of your mock. Your test cases
          should extend or delegate to it. It will automatically registers all created mocks and replay, reset
          or verify them in batch instead of explicitly. Here's an example:</p>

{% highlight java %}
public class SupportTest extends EasyMockSupport {

  private Collaborator firstCollaborator;
  private Collaborator secondCollaborator;
  private ClassTested classUnderTest;

  @Before
  public void setup() {
    classUnderTest = new ClassTested();
  }

  @Test
  public void addDocument() {
    // creation phase
    firstCollaborator = mock(Collaborator.class);
    secondCollaborator = mock(Collaborator.class);
    classUnderTest.addListener(firstCollaborator);
    classUnderTest.addListener(secondCollaborator);

    // recording phase
    firstCollaborator.documentAdded("New Document");
    secondCollaborator.documentAdded("New Document");
    replayAll(); // replay all mocks at once

    // test
    classUnderTest.addDocument("New Document", new byte[0]);
    verifyAll(); // verify all mocks at once
  }
}
{% endhighlight %}

        <p>Alternatively, you can also use <code>EasyMockSupport</code> through delegation as shown below.</p>

{% highlight java %}
public class SupportDelegationTest {

  private EasyMockSupport support = new EasyMockSupport();

  private Collaborator collaborator;

  private ClassTested classUnderTest;

  @Before
  public void setup() {
    classUnderTest = new ClassTested();
  }

  @Test
  public void addDocument() {
    collaborator = support.mock(Collaborator.class);
    classUnderTest.setListener(collaborator);
    collaborator.documentAdded("New Document");
    support.replayAll();
    classUnderTest.addDocument("New Document", "content");
    support.verifyAll();
  }

  @Test
  public void voteForRemovals() {

    IMocksControl ctrl = support.createControl();
    collaborator = ctrl.createMock(Collaborator.class);
    classUnderTest.setListener(collaborator);

    collaborator.documentAdded("Document 1");

    expect(collaborator.voteForRemovals("Document 1")).andReturn((byte) 20);

    collaborator.documentRemoved("Document 1");

    support.replayAll();

    classUnderTest.addDocument("Document 1", "content");
    assertTrue(classUnderTest.removeDocuments("Document 1"));

    support.verifyAll();
  }
}
{% endhighlight %}

        <h2 id="mocking-strict">Strict Mocks</h2>

        <p>On a Mock Object returned by a <code>EasyMock.mock()</code>, the order of method calls is not checked.
          If you would like a strict Mock Object that checks the order of method calls, use <code>EasyMock.<i>strict</i>Mock()</code> to create it.
          The equivalent annotation is <code>@Mock(MockType.STRICT)</code>.</p>

        <p>If an unexpected method is called on a strict Mock Object, the message of the exception will show the method
          calls expected at this point followed by the first conflicting one. <code>verify(mock)</code> shows all missing method calls.</p>

        <h2 id="mocking-nice">Nice Mocks</h2>

        <p>On a Mock Object returned by <code>mock()</code> the default behavior for all methods is to throw an
          <code>AssertionError</code> for all unexpected method calls. If you would like a "nice" Mock Object that by default
          allows all method calls and returns appropriate empty values (<code>0</code>, <code>null</code> or <code>false</code>),
          use <code><i>nice</i>Mock()</code> instead. The equivalent annotation is <code>@Mock(MockType.NICE)</code>.</p>

        <h2 id="mocking-partial">Partial mocking</h2>

        <p>Sometimes you may need to mock only some methods of a class and keep the normal behavior of others. This usually
          happens when you want to test a method that calls some others in the same class. So you want to keep the normal behavior
          of the tested method and mock the others.</p>

        <p>In this case, the first thing to do is to consider a refactoring since most of the time this problem was caused by a
          bad design. If it's not the case, or if you can't do otherwise because of some development constraints, here's the solution:</p>

{% highlight java %}
ToMock mock = partialMockBuilder(ToMock.class)
  .addMockedMethod("mockedMethod").createMock();
{% endhighlight %}

        <p>In this case only the methods added with <code>addMockedMethod(s)</code> will be mocked (<code>mockedMethod()</code> in the example).
          The others will still behave as they used to. One exception: abstract methods are conveniently mocked by default.</p>

        <p><code>partialMockBuilder</code> returns a <code>IMockBuilder</code> interface. It contains various methods to easily create a partial mock.
          Have a look at the javadoc.</p>

        <p><b>Remark:</b> EasyMock provides a default behavior for Object's methods (<i>equals, hashCode, toString, finalize</i>). However, for a
          partial mock, if these methods are not mocked explicitly, they will have their normal behavior instead of EasyMock default's one.</p>

        <h2 id="mocking-self">Self testing</h2>

        <p>It is possible to create a mock by calling one of its constructor. This can be handy when a class method needs to be tested but
          the class other methods, mocked. For that you should do something like</p>

{% highlight java %}
ToMock mock = partialMockBuilder(ToMock.class)
  .withConstructor(1, 2, 3); // 1, 2, 3 are the constructor parameters
{% endhighlight %}

        <p>See the <code>ConstructorCalledMockTest</code> for an example.</p>

        <h2 id="mocking-replace">Replace default class instantiator</h2>

        <p>For some reason (usually an unsupported JVM), it is possible that EasyMock isn't able to mock a class mock in your environment.
          Under the hood, class instantiation is implemented with a factory pattern. In case of failure, you can replace the default instantiator with:</p>

        <ul>
          <li>The good old <code>DefaultClassInstantiator</code> which works well with Serializable classes and otherwise tries to guess
            the best constructor and parameters to use.</li>
          <li>You own instantiator which only needs to implement <code>IClassInstantiator</code>.</li>
        </ul>

        <p>You set this new instantiator using <code>ClassInstantiatorFactory.setInstantiator()</code>. You can set back the default
          one with <code>setDefaultInstantiator()</code>.</p>

        <p><b>Important:</b>The instantiator is kept statically so it will stick between your unit tests. Make sure you reset it if needed.</p>

        <h2 id="mocking-serialize">Serialize a class mock</h2>

        <p>A class mock can also be serialized. However, since it extends a serializable class, this class might have defined a special behavior
          using for instance <code>writeObject</code>. These methods will still be called when serializing the mock and might fail. The workaround is usually to call a constructor when creating the mock.</p>

        <p>Also, de-serializing the mock in a different class loader than the serialization might fail. It wasn't tested.</p>

        <h2 id="mocking-limitations">Class Mocking Limitations</h2>

        <ul>
          <li>To be coherent with interface mocking, EasyMock provides a built-in behavior for <code>equals()</code>, <code>toString()</code>, <code>hashCode()</code> and <code>finalize()</code> even for class mocking. It means that you cannot record your own behavior for these methods. This limitation is considered to be a feature that prevents you from having to care about these methods.</li>
          <li>Final methods cannot be mocked. If called, their normal code will be executed.</li>
          <li>Private methods cannot be mocked. If called, their normal code will be executed. During partial mocking, if your method under test is calling some private methods, you will need to test them as well since you cannot mock them.</li>
          <li>Class instantiation is performed using <a href="http://objenesis.org">Objenesis</a>. Supported JVMs are listed <a href="https://github.com/easymock/objenesis/blob/master/SupportedJVMs.md">here</a>.</li>
        </ul>

        <h2 id="mocking-naming">Naming Mock Objects</h2>

        <p>Mock Objects can be named at creation using <code>mock(String name, Class&lt;T&gt; toMock)</code>, <code>strictMock(String name, Class&lt;T&gt; toMock)</code> or <code>niceMock(String name, Class&lt;T&gt; toMock)</code>. The names will be shown in exception failures.</p>

      </section>
      <!-- #End Mocking -->

      <!-- ******** -->
      <!-- BEHAVIOR -->
      <!-- ******** -->

      <section id="behavior">
        <h1 class="page-header">Behavior</h1>

        <h2 id="behavior-second">A second test</h2>

        <p>Let us write a second test. If a document is added on the class under test, we expect a call to <code>mock.documentAdded()</code> on the Mock Object with the title of the document as argument:</p>

{% highlight java %}
@Test
public void testAddDocument() {
  mock.documentAdded("New Document"); // 2
  replay(mock); // 3
  classUnderTest.addDocument("New Document", new byte[0]);
}
{% endhighlight %}

        <p>So in the record state (before calling <code>replay</code>), the Mock Object does <em>not</em> behave like a Mock Object, but it records method calls. After calling <code>replay</code>, it behaves like a Mock Object, checking whether the expected method calls are really done.</p>

        <p>If <code>classUnderTest.addDocument("New Document", new byte[0])</code> calls the expected method with a wrong argument, the Mock Object will complain with an <code>AssertionError</code>:</p>

{% highlight java %}
java.lang.AssertionError:
  Unexpected method call documentAdded("Wrong title"):
    documentAdded("New Document"): expected: 1, actual: 0
      at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29)
      at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:44)
      at $Proxy0.documentAdded(Unknown Source)
      at org.easymock.samples.ClassUnderTest.notifyListenersDocumentAdded(ClassUnderTest.java:61)
      at org.easymock.samples.ClassUnderTest.addDocument(ClassUnderTest.java:28)
      at org.easymock.samples.ExampleTest.testAddDocument(ExampleTest.java:30)
      ...
{% endhighlight %}

       <p>All missed expectations are shown, as well as all fulfilled expectations for the unexpected call (none in this case). If the method call is executed too often, the Mock Object complains, too:</p>

{% highlight java %}
java.lang.AssertionError:
  Unexpected method call documentAdded("New Document"):
    documentAdded("New Document"): expected: 1, actual: 2
      at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29)
      at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:44)
      at $Proxy0.documentAdded(Unknown Source)
      at org.easymock.samples.ClassUnderTest.notifyListenersDocumentAdded(ClassUnderTest.java:62)
      at org.easymock.samples.ClassUnderTest.addDocument(ClassUnderTest.java:29)
      at org.easymock.samples.ExampleTest.testAddDocument(ExampleTest.java:30)
      ...
{% endhighlight %}

        <h2 id="behavior-same-method">Changing Behavior for the Same Method Call</h2>

        <p>It is also possible to specify a changing behavior for a method. The methods <code>times</code>, <code>andReturn</code>, and <code>andThrow</code> may be chained. As an example, we define <code>voteForRemoval("Document")</code> to</p>

        <ul>
          <li>return 42 for the first three calls,</li>
          <li>throw a <code>RuntimeException</code> for the next four calls,</li>
          <li>return -42 once.</li>
        </ul>

{% highlight java %}
expect(mock.voteForRemoval("Document"))
  .andReturn((byte) 42).times(3)
  .andThrow(new RuntimeException(), 4)
  .andReturn((byte) -42);
{% endhighlight %}

        <h2 id="behavior-default">Altering EasyMock default behavior</h2>

        <p>EasyMock provides a property mechanisim allowing to alter its behavior. It mainly aims at allowing to use a legacy behavior on a new version. Currently supported properties are:</p>

        <dl>
          <dt><code>easymock.notThreadSafeByDefault</code></dt>
          <dd>If true, a mock won't be thread-safe by default. Possible values are "true" or "false". Default is false</dd>

          <dt><code>easymock.enableThreadSafetyCheckByDefault</code></dt>
          <dd>If true, thread-safety check feature will be on by default. Possible values are "true" or "false". Default is false</dd>

          <dt><code>easymock.disableClassMocking</code></dt>
          <dd>Do not allow class mocking (only allow interface mocking). Possible values are "true" or "false". Default is false.</dd>
        </dl>

        <p>Properties can be set in two ways.</p>

        <ul>
          <li>In an <code>easymock.properties</code> file set in the classpath default package</li>
          <li>By calling <code>EasyMock.setEasyMockProperty</code>. Constants are available in the <code>EasyMock</code> class. Setting properties in the code obviously override any property set in <code>easymock.properties</code></li>
        </ul>

        <h2 id="behavior-object">Object Methods</h2>

        <p>The behavior for the four Object methods <code>equals()</code>, <code>hashCode()</code>, <code>toString()</code> and <code>finalize()</code> cannot be changed for Mock Objects created with EasyMock, even if they are part of the interface for which the Mock Object is created.</p>

        <h2 id="behavior-stub">Using Stub Behavior for Methods</h2>

        <p>Sometimes, we would like our Mock Object to respond to some method calls, but we do not want to check how often they are called, when they are called, or even if they are called at all. This stub behavoir may be defined by using the methods <code>andStubReturn(Object value)</code>, <code>andStubThrow(Throwable throwable)</code>, <code>andStubAnswer(IAnswer&lt;T&gt; answer)</code> and <code>asStub()</code>. The following code configures the MockObject to answer 42 to <code>voteForRemoval("Document")</code> once and -1 for all other arguments:</p>

{% highlight java %}
expect(mock.voteForRemoval("Document")).andReturn(42);
expect(mock.voteForRemoval(not(eq("Document")))).andStubReturn(-1);
{% endhighlight %}

        <h2 id="behavior-reusing">Reusing a Mock Object</h2>

        <p>Mock Objects may be reset by <code>reset(mock)</code>.</p>

        <p>If needed, a mock can also be converted from one type to another by calling <code>resetToNice(mock)</code>, <code>resetToDefault(mock)</code> or <code>resetToStrict(mock)</code>.</p>

      </section>
      <!-- #End Behavior -->

      <!-- ************ -->
      <!-- VERIFICATION -->
      <!-- ************ -->

      <section id="verification">
        <h1 class="page-header">Verification</h1>

        <h2 id="verification-first">A first verification</h2>

        <p>There is one error that we have not handled so far: If we specify behavior, we would like to verify that it is actually used. The current test would pass if no method on the Mock Object is called. To verify that the specified behavior has been used, we have to call <code>verify(mock)</code>:</p>

{% highlight java %}
@Test
public void testAddDocument() {
  mock.documentAdded("New Document"); // 2
  replay(mock); // 3
  classUnderTest.addDocument("New Document", new byte[0]);
  verify(mock);
}
{% endhighlight %}

        <p>If the method is not called on the Mock Object, we now get the following exception:</p>

{% highlight java %}
java.lang.AssertionError:
  Expectation failure on verify:
    documentAdded("New Document"): expected: 1, actual: 0
      at org.easymock.internal.MocksControl.verify(MocksControl.java:70)
      at org.easymock.EasyMock.verify(EasyMock.java:536)
      at org.easymock.samples.ExampleTest.testAddDocument(ExampleTest.java:31)
      ...
{% endhighlight %}

        <p>The message of the exception lists all missed expectations.</p>

        <h2 id="verification-calls">Expecting an Explicit Number of Calls</h2>

        <p>Up to now, our test has only considered a single method call. The next test should check whether the addition of an already existing document leads to a call to <code>mock.documentChanged()</code> with the appropriate argument. To be sure, we check this three times (hey, it is an example ;-)):</p>

{% highlight java %}
@Test
public void testAddAndChangeDocument() {
  mock.documentAdded("Document");
  mock.documentChanged("Document");
  mock.documentChanged("Document");
  mock.documentChanged("Document");
  replay(mock);
  classUnderTest.addDocument("Document", new byte[0]);
  classUnderTest.addDocument("Document", new byte[0]);
  classUnderTest.addDocument("Document", new byte[0]);
  classUnderTest.addDocument("Document", new byte[0]);
  verify(mock);
}
{% endhighlight %}

        <p>To avoid the repetition of <code>mock.documentChanged("Document")</code>, EasyMock provides a shortcut. We may specify the call count with the method <code>times(int times)</code> on the object returned by <code>expectLastCall()</code>. The code then looks like:</p>

{% highlight java %}
@Test
public void testAddAndChangeDocument() {
  mock.documentAdded("Document");
  mock.documentChanged("Document");
  expectLastCall().times(3);
  replay(mock);
  classUnderTest.addDocument("Document", new byte[0]);
  classUnderTest.addDocument("Document", new byte[0]);
  classUnderTest.addDocument("Document", new byte[0]);
  classUnderTest.addDocument("Document", new byte[0]);
  verify(mock);
}
{% endhighlight %}

        <p>If the method is called too often, we get an exception that tells us that the method has been called too many times. The failure occurs immediately at the first method call exceeding the limit:</p>

{% highlight java %}
java.lang.AssertionError:
  Unexpected method call documentChanged("Document"):
    documentChanged("Document"): expected: 3, actual: 4
      at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29)
      at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:44)
      at $Proxy0.documentChanged(Unknown Source)
      at org.easymock.samples.ClassUnderTest.notifyListenersDocumentChanged(ClassUnderTest.java:67)
      at org.easymock.samples.ClassUnderTest.addDocument(ClassUnderTest.java:26)
      at org.easymock.samples.ExampleTest.testAddAndChangeDocument(ExampleTest.java:43)
      ...
{% endhighlight %}

        <p>If there are too few calls, <code>verify(mock)</code> throws an <code>AssertionError</code>:</p>
{% highlight java %}
java.lang.AssertionError:
  Expectation failure on verify:
    documentChanged("Document"): expected: 3, actual: 2
      at org.easymock.internal.MocksControl.verify(MocksControl.java:70)
      at org.easymock.EasyMock.verify(EasyMock.java:536)
      at org.easymock.samples.ExampleTest.testAddAndChangeDocument(ExampleTest.java:43)
      ...
{% endhighlight %}

        <h2 id="verification-return">Specifying Return Values</h2>

        <p>For specifying return values, we wrap the expected call in <code>expect(T value)</code> and specify the return value with the method <code>andReturn(Object returnValue)</code> on the object returned by <code>expect(T value)</code>.</p>

        <p>As an example, we check the workflow for document removal. If <code>ClassUnderTest</code> gets a call for document removal, it asks all collaborators for their vote for removal with calls to <code>byte voteForRemoval(String title)</code> value. Positive return values are a vote for removal. If the sum of all values is positive, the document is removed and <code>documentRemoved(String title)</code> is called on all collaborators:</p>

{% highlight java %}
@Test
public void testVoteForRemoval() {
  mock.documentAdded("Document");
  // expect document addition
  // expect to be asked to vote for document removal, and vote for it
  expect(mock.voteForRemoval("Document")).andReturn((byte) 42);
  mock.documentRemoved("Document");
  // expect document removal
  replay(mock);
  classUnderTest.addDocument("Document", new byte[0]);
  assertTrue(classUnderTest.removeDocument("Document"));
  verify(mock);
}

@Test
public void testVoteAgainstRemoval() {
  mock.documentAdded("Document");
  // expect document addition
  // expect to be asked to vote for document removal, and vote against it
  expect(mock.voteForRemoval("Document")).andReturn((byte) -42);
  replay(mock);
  classUnderTest.addDocument("Document", new byte[0]);
  assertFalse(classUnderTest.removeDocument("Document"));
  verify(mock);
}
{% endhighlight %}

        <p>The type of the returned value is checked at compile time. As an example, the following code will not compile, as the type of the provided return value does not match the method's return value:</p>

{% highlight java %}
expect(mock.voteForRemoval("Document")).andReturn("wrong type");
{% endhighlight %}

        <p>Instead of calling <code>expect(T value)</code> to retrieve the object for setting the return value, we may also use the object returned by <code>expectLastCall()</code>. Instead of</p>

{% highlight java %}
expect(mock.voteForRemoval("Document")).andReturn((byte) 42);
{% endhighlight %}

        <p>we may use</p>

{% highlight java %}
mock.voteForRemoval("Document");
expectLastCall().andReturn((byte) 42);
{% endhighlight %}

        <p>This type of specification should only be used if the line gets too long, as it does not support type checking at compile time.</p>

        <h2 id="verification-exceptions">Working with Exceptions</h2>

        <p>For specifying exceptions (more exactly: Throwables) to be thrown, the object returned by <code>expectLastCall()</code> and <code>expect(T value)</code> provides the method <code>andThrow(Throwable throwable)</code>. The method has to be called in record state after the call to the Mock Object for which it specifies the <code>Throwable</code> to be thrown.</p>

        <p>Unchecked exceptions (that is, <code>RuntimeException</code>, <code>Error</code> and all their subclasses) can be thrown from every method. Checked exceptions can only be thrown from the methods that do actually throw them.</p>

        <h2 id="verification-creating">Creating Return Values or Exceptions</h2>

        <p>Sometimes we would like our mock object to return a value or throw an exception that is created at the time of the actual call. Since EasyMock 2.2, the object returned by <code>expectLastCall()</code> and <code>expect(T value)</code> provides the method <code>andAnswer(IAnswer answer)</code> which allows to specify an implementation of the interface <code>IAnswer</code> that is used to create the return value or exception.</p>

        <p>Inside an <code>IAnswer</code> callback, the arguments passed to the mock call are available via <code>EasyMock.getCurrentArgument(int index)</code>. If you use these, refactorings like reordering parameters may break your tests. You have been warned.</p>

        <p>An alternative to <code>IAnswer</code> are the <code>andDelegateTo</code> and <code>andStubDelegateTo</code> methods. They allow to delegate the call to a concrete implementation of the mocked interface that will then provide the answer. The pros are that the arguments found in <code>EasyMock.getCurrentArgument()</code> for <code>IAnswer</code> are now passed to the method of the concrete implementation. This is refactoring safe. The cons are that you have to provide an implementation which is kind of doing a mock manually... Which is what you try to avoid by using EasyMock. It can also be painful if the interface has many methods. Finally, the type of the concrete class can't be checked statically against the mock type. If for some reason, the concrete class isn't implementing the method that is delegated, you will get an exception during the replay only. However, this case should be quite rare.</p>

        <p>To understand correctly the two options, here is an example:</p>

{% highlight java %}
List<String> l = mock(List.class);

// andAnswer style
expect(l.remove(10)).andAnswer(() -> getCurrentArgument(0).toString());

// andDelegateTo style
expect(l.remove(10)).andDelegateTo(new ArrayList<String>() {
  @Override
  public String remove(int index) {
    return Integer.toString(index);
  }
});
{% endhighlight %}

        <h2 id="verification-order">Checking Method Call Order Between Mocks</h2>

        <p>Up to this point, we have seen a mock object as a single object that is configured by static methods on the class <code>EasyMock</code>. But many of these static methods just identify the hidden control of the Mock Object and delegate to it. A Mock Control is an object implementing the <code>IMocksControl</code> interface.</p>

        <p>So instead of</p>

{% highlight java %}
IMyInterface mock = strictMock(IMyInterface.class);
replay(mock);
verify(mock);
reset(mock);
{% endhighlight %}

        <p>we may use the equivalent code:</p>

{% highlight java %}
IMocksControl ctrl = createStrictControl();
IMyInterface mock = ctrl.createMock(IMyInterface.class);
ctrl.replay();
ctrl.verify();
ctrl.reset();
{% endhighlight %}

        <p>The IMocksControl allows to create more than one Mock Object, and so it is possible to check the order of method calls between mocks. As an example, we set up two mock objects for the interface <code>IMyInterface</code>, and we expect the calls <code>mock1.a()</code> and <code>mock2.a()</code> ordered, then an open number of calls to <code>mock1.c()</code> and <code>mock2.c()</code>, and finally <code>mock2.b()</code> and <code>mock1.b()</code>, in this order:</p>

{% highlight java %}
IMocksControl ctrl = createStrictControl();
IMyInterface mock1 = ctrl.createMock(IMyInterface.class);
IMyInterface mock2 = ctrl.createMock(IMyInterface.class);
mock1.a();
mock2.a();
ctrl.checkOrder(false);
mock1.c();
expectLastCall().anyTimes();
mock2.c();
expectLastCall().anyTimes();
ctrl.checkOrder(true);
mock2.b();
mock1.b();
ctrl.replay();
{% endhighlight %}

        <h2 id="verification-relaxing">Relaxing Call Counts</h2>
        <p>To relax the expected call counts, there are additional methods that may be used instead of <code>times(int count)</code>:</p>
        <dl>
          <dt><code>times(int min, int max)</code></dt>
          <dd>to expect between <code>min</code> and <code>max</code> calls,</dd>

          <dt><code>atLeastOnce()</code></dt>
          <dd>to expect at least one call, and</dd>

          <dt><code>anyTimes()</code></dt>
          <dd>to expected an unrestricted number of calls.</dd>
        </dl>
        <p>If no call count is specified, one call is expected. If we would like to state this explicitely, <code>once()</code> or <code>times(1)</code> may be used.</p>

        <h2 id="verification-switching">Switching Order Checking On and Off</h2>

        <p>Sometimes, it is necessary to have a Mock Object that checks the order of only some calls. In record phase, you may switch order checking on by calling <code>checkOrder(mock, true)</code> and switch it off by calling <code>checkOrder(mock, false)</code>.</p>

        <p>There are two differences between a strict Mock Object and a normal Mock Object:</p>
        <ol>
          <li>A strict Mock Object has order checking enabled after creation.</li>
          <li>A strict Mock Object has order checking enabled after reset (see <em>Reusing a Mock Object</em>).</li>
        </ol>

        <h2 id="verification-expectations">Flexible Expectations with Argument Matchers</h2>

        <p>To match an actual method call on the Mock Object with an expectation, <code>Object</code> arguments are by default compared with <code>equals()</code>. Arrays are
          by default <span class="badge">since 3.5</span> compared with <code>Arrays.equals()</code>.</p>

        <p>But once in a while, you will want to match you parameter in a different way. As an example, we consider the following expectation:</p>

{% highlight java %}
Document document = getFromCache();
expect(mock.voteForRemovals(document)).andReturn(42);
{% endhighlight %}

        <p>Here, I don't want the document received by <code>voteForRemovals</code> to be equals,
          I want it to be the exact same class instance coming from the cache. My current expectation
          is not testing what I want.</p>

        <p>To specify that the exact same instance is needed for this call, we use the method
          <code>same</code> that is statically imported from the <code>EasyMock</code> class:</p>

{% highlight java %}
Document document = getFromCache();
expect(mock.voteForRemovals(same(document))).andReturn(42);
{% endhighlight %}

        <p><b>Important:</b> When you use matchers in a call, you have to specify matchers <b>for all arguments of the method call</b>.</p>

        <p>There are a couple of predefined argument matchers available.</p>

        <dl>
          <dt><code>eq(X value)</code></dt>
          <dd>Matches if the actual value is equals the expected value. Available for all primitive types and for objects.</dd>

          <dt><code>anyBoolean()</code>, <code>anyByte()</code>, <code>anyChar()</code>, <code>anyDouble()</code>, <code>anyFloat()</code>, <code>anyInt()</code>, <code>anyLong()</code>, <code>anyObject()</code>, <code>anyObject(Class clazz)</code>, <code>anyShort()</code>, <code>anyString()</code></dt>
          <dd>Matches any value. Available for all primitive types and for objects.</dd>

          <dt><code>eq(X value, X delta)</code></dt>
          <dd>Matches if the actual value is equal to the given value allowing the given delta. Available for <code>float</code> and <code>double</code>.</dd>

          <dt><code>aryEq(X value)</code></dt>
          <dd>Matches if the actual value is equal to the given value according to <code>Arrays.equals()</code>. Available for primitive and object arrays.</dd>

          <dt><code>isNull()</code>, <code>isNull(Class clazz)</code></dt>
          <dd>Matches if the actual value is null. Available for objects.</dd>

          <dt><code>notNull()</code>, <code>notNull(Class clazz)</code></dt>
          <dd>Matches if the actual value is not null. Available for objects.</dd>

          <dt><code>same(X value)</code></dt>
          <dd>Matches if the actual value is the same as the given value. Available for objects.</dd>

          <dt><code>isA(Class clazz)</code></dt>
          <dd>Matches if the actual value is an instance of the given class, or if it is in instance of a class that extends or implements the given class. Null always return false. Available for objects.</dd>

          <dt><code>lt(X value)</code>, <code>leq(X value)</code>, <code>geq(X value)</code>, <code>gt(X value)</code></dt>
          <dd>Matches if the actual value is less/less or equal/greater or equal/greater than the given value. Available for all numeric primitive types and <code>Comparable</code>.</dd>

          <dt><code>startsWith(String prefix), contains(String substring), endsWith(String suffix)</code></dt>
          <dd>Matches if the actual value starts with/contains/ends with the given value. Available for <code>String</code>s.</dd>

          <dt><code>matches(String regex), find(String regex)</code></dt>
          <dd>Matches if the actual value/a substring of the actual value matches the given regular expression. Available for <code>String</code>s.</dd>

          <dt><code>and(X first, X second)</code></dt>
          <dd>Matches if the matchers used in <code>first</code> and <code>second</code> both match. Available for all primitive types and for objects.</dd>

          <dt><code>or(X first, X second)</code></dt>
          <dd>Matches if one of the matchers used in <code>first</code> and <code>second</code> match. Available for all primitive types and for objects.</dd>

          <dt><code>not(X value)</code></dt>
          <dd>Matches if the matcher used in <code>value</code> does not match.</dd>

          <dt><code>cmpEq(X value)</code></dt>
          <dd>Matches if the actual value is equals according to <code>Comparable.compareTo(X o)</code>. Available for all numeric primitive types and <code>Comparable</code>.</dd>

          <dt><code>cmp(X value, Comparator&lt;X&gt; comparator, LogicalOperator operator)</code></dt>
          <dd>Matches if <code>comparator.compare(actual, value) operator 0</code> where the operator is &lt;,&lt;=,&gt;,&gt;= or ==. Available for objects.</dd>

          <dt><code>capture(Capture&lt;T&gt; capture)</code>, <code>captureXXX(Capture&lt;T&gt; capture)</code></dt>
          <dd>Matches any value but captures it in the <code>Capture</code> parameter for later access. You can do <code>and(someMatcher(...), capture(c))</code> to capture a parameter from a specific call to the method. You can also specify a <code>CaptureType</code> telling that a given <code>Capture</code> should keep the first, the last, all or no captured values.</dd>
        </dl>

        <h2 id="verification-matchers">Defining your own Argument Matchers</h2>

        <p>Sometimes it is desirable to define own argument matchers. Let's say that an argument matcher is needed that matches an exception if the given exception has the same type and an equal message. It should be used this way:</p>

{% highlight java %}
IllegalStateException e = new IllegalStateException("Operation not allowed.")
expect(mock.logThrowable(eqException(e))).andReturn(true);
{% endhighlight %}

        <p>Two steps are necessary to achieve this: The new argument matcher has to be defined, and the static method <code>eqException</code> has to be declared.</p>

        <p>To define the new argument matcher, we implement the interface <code>org.easymock.IArgumentMatcher</code>. This interface contains two methods: <code>matches(Object actual)</code> checks whether the actual argument matches the given argument, and <code>appendTo(StringBuffer buffer)</code> appends a string representation of the argument matcher to the given string buffer. The implementation is straightforward:</p>

{% highlight java %}
import org.easymock.IArgumentMatcher;

public class ThrowableEquals implements IArgumentMatcher {

  private Throwable expected;

  public ThrowableEquals(Throwable expected) {
    this.expected = expected;
  }

  public boolean matches(Object actual) {
    if (!(actual instanceof Throwable)) {
      return false;
    }

    String actualMessage = ((Throwable) actual).getMessage();
    return expected.getClass().equals(actual.getClass()) &amp;&amp; expected.getMessage().equals(actualMessage);
  }

  public void appendTo(StringBuffer buffer) {
    buffer.append("eqException(");
    buffer.append(expected.getClass().getName());
    buffer.append(" with message \"");
    buffer.append(expected.getMessage());
    buffer.append("\"")");
  }
}
{% endhighlight %}

        <p>The method <code>eqException</code> must create the argument matcher with the given Throwable, report it to EasyMock via the static method <code>reportMatcher(IArgumentMatcher matcher)</code>, and return a value so that it may be used inside the call (typically <code>0</code>, <code>null</code> or <code>false</code>). A first attempt may look like:</p>

{% highlight java %}
public static Throwable eqException(Throwable in) {
  EasyMock.reportMatcher(new ThrowableEquals(in));
  return null;
}
{% endhighlight %}

        <p>However, this only works if the method <code>logThrowable</code> in the example usage accepts <code>Throwable</code>s, and does not require something more specific like a <code>RuntimeException</code>. In the latter case, our code sample would not compile:</p>

{% highlight java %}
IllegalStateException e = new IllegalStateException("Operation not allowed.")
expect(mock.logThrowable(eqException(e))).andReturn(true);
{% endhighlight %}

        <p>Java 5.0 to the rescue: Instead of defining <code>eqException</code> with a <code>Throwable</code> as parameter and return value, we use a generic type that extends <code>Throwable</code>:</p>

{% highlight java %}
public static&lt;T extends Throwable&gt;T eqException(T in) {
  reportMatcher(new ThrowableEquals(in));
  return null;
}
{% endhighlight %}

      </section>
      <!-- #End Verification -->

      <!-- **** -->
      <!-- Advanced -->
      <!-- **** -->

      <section id="advanced">
        <h1 class="page-header">Advanced</h1>

        <h2 id="advanced-serializing">Serializing Mocks</h2>

        <p>Mocks can be serialized at any time during their life. However, there are some obvious constraints:</p>

        <ul>
          <li>All used matchers should be serializable (all genuine EasyMock ones are)</li>
          <li>Recorded parameters should also be serializable</li>
        </ul>

        <h2 id="advanced-multithreading">Multithreading</h2>

        <p>During recording, a mock is <b>not</b> thread-safe. So a giving mock (or mocks linked to the same <code>IMocksControl</code>) can only be recorded from a single thread. However, different mocks can be recorded simultaneously in different threads.</p>

        <p>During the replay phase, mocks are by default thread-safe. This can be change for a given mock if <code>makeThreadSafe(mock, false)</code> is called during the recording phase. This can prevent deadlocks in some rare situations.</p>

        <p>Finally, calling <code>checkIsUsedInOneThread(mock, true)</code> on a mock will make sure the mock is used in only one thread and throw an exception otherwise. This can be handy to make sure a thread-unsafe mocked object is used correctly.</p>

        <h2 id="advanced-osgi">OSGi</h2>

        <p>EasyMock jar can be used as an OSGi bundle. It exports <code>org.easymock</code>, <code>org.easymock.internal</code> and <code>org.easymock.internal.matchers</code> packages. However, to import the two latter, you need to specify the <code>poweruser</code> attribute at true (<code>poweruser=true</code>). These packages are meant to be used to extend EasyMock so they usually don't need to be imported.</p>

        <h2 id="advanced-compatibility">Backward Compatibility</h2>

        <p>EasyMock 3 still has a Class Extension project (although deprecated) to allow an easier migration from EasyMock 2 to EasyMock 3. It is a source not a binary compatibility. So the code will need to be recompiled.</p>

        <p>EasyMock 2.1 introduced a callback feature that has been removed in EasyMock 2.2, as it was too complex. Since EasyMock 2.2, the <code>IAnswer</code> interface provides the functionality for callbacks.</p>

      </section>
      <!-- #End Advanced -->

    </div>
    <!-- #End content -->

    <!-- side menu -->
    <div class="col-md-2">
      <div id="sidebar" class="sidebar hidden-print visible-md visible-lg affix-top" role="complementary" data-spy="affix" data-offset-top="54">
        <ul class="nav">
          <li><a href="#installation">Installation</a>
            <ul class="nav">
              <li><a href="#installation-requirements">Requirements</a></li>
              <li><a href="#installation-using-maven">Using Maven</a></li>
              <li><a href="#installation-standalone">Standalone</a></li>
              <li><a href="#installation-android">Android</a></li>
            </ul>
          </li>
          <li><a href="#mocking">Mocking</a>
            <ul class="nav">
              <li><a href="#mocking-first">The first Mock Object</a></li>
              <li><a href="#mocking-annotations">Using annotations</a></li>
              <li><a href="#mocking-support">EasyMockSupport</a></li>
              <li><a href="#mocking-strict">Strict Mocks</a></li>
              <li><a href="#mocking-nice">Nice Mocks</a></li>
              <li><a href="#mocking-partial">Partial mocking</a></li>
              <li><a href="#mocking-self">Self testing</a></li>
              <li><a href="#mocking-replace">Replace default class instantiator</a></li>
              <li><a href="#mocking-serialize">Serialize a class mock</a></li>
              <li><a href="#mocking-limitations">Class Mocking Limitations</a></li>
              <li><a href="#mocking-naming">Naming Mock Objects</a></li>
            </ul>
          </li>
          <li><a href="#behavior">Behavior</a>
            <ul class="nav">
              <li><a href="#behavior-second">A second test</a></li>
              <li><a href="#behavior-same-method">Changing Behavior for the Same Method Call</a></li>
              <li><a href="#behavior-default">Altering EasyMock default behavior</a></li>
              <li><a href="#behavior-object">Object Methods</a></li>
              <li><a href="#behavior-stub">Using Stub Behavior for Methods</a></li>
              <li><a href="#behavior-reusing">Reusing a Mock Object</a></li>
            </ul>
          </li>
          <li><a href="#verification">Verification</a>
            <ul class="nav">
              <li><a href="#verification-first">A first verification</a></li>
              <li><a href="#verification-calls">Expecting an Explicit Number of Calls</a></li>
              <li><a href="#verification-return">Specifying Return Values</a></li>
              <li><a href="#verification-exceptions">Working with Exceptions</a></li>
              <li><a href="#verification-creating">Creating Return Values or Exceptions</a></li>
              <li><a href="#verification-order">Checking Method Call Order Between Mocks</a></li>
              <li><a href="#verification-relaxing">Relaxing Call Counts</a></li>
              <li><a href="#verification-switching">Switching Order Checking On and Off</a></li>
              <li><a href="#verification-expectations">Flexible Expectations with Argument Matchers</a></li>
              <li><a href="#verification-matchers">Defining your own Argument Matchers</a></li>
            </ul>
          </li>
          <li><a href="#advanced">Advanced</a>
            <ul class="nav">
              <li><a href="#advanced-serializing">Serializing Mocks</a></li>
              <li><a href="#advanced-multithreading">Multithreading</a></li>
              <li><a href="#advanced-osgi">OSGi</a></li>
              <li><a href="#advanced-compatibility">Backward Compatibility</a></li>
            </ul>
          </li>
        </ul>
        <a class="back-to-top" href="#top">Back to top</a>
      </div>
    </div>

  </div>
</div>
